//
//  LXSearchViewController.m
//  INMOTION_CUSTOM
//
//  Created by wucw on 2022/4/29.
//  Copyright © 2022 cjg. All rights reserved.
//

#import "LXSearchViewController.h"
#import "IMTConfig.h"
#import "LXSearchDeviceCell.h"
#import "NSObject+HUD.h"
#import "KSLanguageManager.h"
#import "AppTypeTool.h"
#import "UIImage+Category.h"
#import "CarModel.h"

@interface LXSearchViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIImageView *bleImageView;
@property (nonatomic, strong) UILabel *status;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *bottomButton;
@property (nonatomic, strong) NSTimer *startScanTimer;
@property (nonatomic, strong) NSTimer *stopScanTimer;
@property (nonatomic, strong) NSDate *startScanDateTime;

@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *dataArray;

@end

@implementation LXSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    
    [self addSubviews];
//    [self setConnecting];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroundNotification) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)appWillEnterForegroundNotification {
    [self startAnimations:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
//    // 搜索中、连接中 开启动画
//    if (self.bleManagerState == KSBLEManagerStateScanning || self.bleManagerState ==  KSBLEManagerStateConnecting) {
//        [self startAnimations:YES];
//    }
    
    [self startScan];
}

- (void)setBLEManagerStat:(KSBLEManagerState)state {
    self.bleManagerState = state;
    switch (state) {
        case KSBLEManagerStateScanning:
            // 搜索中
            break;
        case KSBLEManagerStateConnecting:
            // 连接中
            [self setConnecting];
            break;
        case KSBLEManagerStateConnected:
            // 已连接
            break;
            
        default:
            break;
    }
    
}

- (void)startScan {
    self.status.text = IMTNewCarLocalizedString(@"searching");
    self.tableView.hidden = false;
    self.peripheral = nil;
    [self startAnimations:YES];
    [self.bottomButton setTitle:IMTNewCarLocalizedString(@"stop_searching") forState:UIControlStateNormal];
    
    [self.dataArray removeAllObjects];
    [self.tableView reloadData];
    
    
    [self.startScanTimer invalidate];
    self.startScanTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(scanTimeout) userInfo:nil repeats:NO];
    self.startScanDateTime = [NSDate date];
    
    // 1秒以内如果搜索到设备
    [self.stopScanTimer invalidate];
    self.stopScanTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(stopScanTimerFired) userInfo:nil repeats:NO];
    
    WS(weakSelf)
    [[KSBLEManager sharedManager] startScanWithBlock:^(NSError *error, NSArray<CBPeripheral *> *peripherals) {
        if (error) {
            [self showErrorHUDWithText:error.description];
        }else {
            weakSelf.dataArray = peripherals.mutableCopy;
//            [weakSelf.dataArray addObjectsFromArray:weakSelf.dataArray];
//            [weakSelf.dataArray addObjectsFromArray:weakSelf.dataArray];
//            [weakSelf.dataArray addObjectsFromArray:weakSelf.dataArray];
//            [weakSelf.dataArray addObjectsFromArray:weakSelf.dataArray];
            [weakSelf.tableView reloadData];
            
            // 扫描时间超过一秒时，搜索到设备后停止搜索
            if ([[NSDate date] timeIntervalSinceDate:self.startScanDateTime] > 1) {
                [self stopScanTimerFired];
            }
        }
    }];
    
}

- (void)scanTimeout {
    [self.startScanTimer invalidate];
    NSLog(@"startScanTimerFired");
    [self stopScan:IMTNewCarLocalizedString(@"search_stopped") stopAnimation:YES];
    [self startAnimations:NO];
}

- (void)stopScanTimerFired {
    [self.stopScanTimer invalidate];
    if (self.dataArray.count > 0 && self.bleManagerState == KSBLEManagerStateScanning) {
        [self scanTimeout];
    }
}

- (void)stopScan:(NSString *)status stopAnimation:(BOOL)stopAnimation {
    [self.stopScanTimer invalidate];
    if (self.startScanTimer.isValid) {
        [self.startScanTimer invalidate];
    }
    
    self.status.text = status;
    [self startAnimations:!stopAnimation];
    [[KSBLEManager sharedManager] stopScan];
    [self.bottomButton setTitle:IMTNewCarLocalizedString(@"search_again") forState:UIControlStateNormal];
}

- (void)setConnecting {
    // 停止扫描
    [self stopScan:IMTNewCarLocalizedString(@"connecting") stopAnimation:NO];
    self.tableView.hidden = true;
    [self.bottomButton setTitle:IMTNewCarLocalizedString(@"search_again") forState:UIControlStateNormal];
}

- (void)setConnectedFaild {
    self.status.text = IMTNewCarLocalizedString(@"connect_failed");
    self.tableView.hidden = true;
    [self.bottomButton setTitle:IMTNewCarLocalizedString(@"search_again") forState:UIControlStateNormal];
    [self startAnimations:false];
}


- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self startAnimations:NO];
    [self.startScanTimer invalidate];
    [self.stopScanTimer invalidate];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)addSubviews {
    [self.view addSubview:self.imageView];
    [self.view addSubview:self.bleImageView];
    [self.view addSubview:self.status];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomButton];
    [self.tableView registerNib:[UINib nibWithNibName:@"LXSearchDeviceCell" bundle:nil] forCellReuseIdentifier:@"cell"];
}

/// 重新搜索
- (void)bottomClick {
    if ([_bottomButton.titleLabel.text isEqualToString:IMTNewCarLocalizedString(@"stop_searching")] || self.bleManagerState == KSBLEManagerStateScanning) {
        [self stopScan:IMTNewCarLocalizedString(@"search_stopped") stopAnimation:YES];
        return;
    }
    if (self.peripheral) {
        // 取消连接
        [[KSBLEManager sharedManager] cancelConnection:self.peripheral];
    }
    [self startScan];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LXSearchDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[LXSearchDeviceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
        
    CBPeripheral *peripheral = self.dataArray[indexPath.row];
//    [cell setTitle:peripheral.name];
    NSArray *strs = [peripheral.name componentsSeparatedByString:@"-"];
    if (strs.count > 0) {
        [cell setTitle:[NSString stringWithFormat:@"%@-%@", E20VegogoPrefix, strs.lastObject]];
    } else {
        [cell setTitle:[NSString stringWithFormat:@"%@-%@", E20VegogoPrefix, peripheral.name]];
    }
    [cell setLogImage: ([strs.firstObject isEqual:E20VegogoPrefix] || [strs.firstObject isEqual:E20InmotionPrefix]) ? @"e20_icon" : @"ic_device_type_scooter"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchBlock) {
        CBPeripheral *peripheral = self.dataArray[indexPath.row];
        self.peripheral = peripheral;
        self.searchBlock(peripheral);
        [self setConnecting];
    }
}



- (void)startAnimations:(BOOL)start {
    NSLog(@"startAnimations ---- %@",start == true ? @"YES" : @"NO");
    if (start) {
        self.imageView.image = [UIImage imageNamed: @"img_search_circle"];
        [self rotate360DegreeWithImageView:self.imageView withCircle:1000];
    } else {
        [self.imageView.layer removeAllAnimations];
        self.imageView.image = [UIImage imageNamed:@"car_speed_out_circle"];
    }
}


///
/// 图片360°旋转
/// [imageView.layer removeAllAnimations];  //  停止转动
///
- (UIImageView *)rotate360DegreeWithImageView:(UIImageView *)imageView withCircle:(int)circle {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI*0.5, 0.0, 0.0, 1.0) ];  // 围绕Z轴旋转，垂直与屏幕
    animation.duration = 1; // 旋转速度
    animation.cumulative = YES; // 旋转效果累计，先转180度，接着再旋转180度，从而实现360旋转
    animation.repeatCount = 4 * circle;   // 旋转圈数，4为一圈
    [imageView.layer addAnimation:animation forKey:nil];
    return imageView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img_search_circle"]];
        _imageView.frame = CGRectMake(kIMTScreenWidth * 0.15, kIMTScreenHeight * 0.05, kIMTScreenWidth * 0.7, kIMTScreenWidth * 0.7);
    }
    return _imageView;
}

- (UIImageView *)bleImageView {
    if (!_bleImageView) {
        _bleImageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"ic_ble_in_searching"] imgWithTintColor: [AppTypeTool getThemeColor]]];
        _bleImageView.frame = CGRectMake(0, 0, 35, 50);
        _bleImageView.center = CGPointMake(self.imageView.center.x, self.imageView.center.y - 20);
        [self.view addSubview:_bleImageView];
    }
    return _bleImageView;
}

- (UILabel *)status {
    if (!_status) {
        _status = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kIMTScreenWidth * 0.7 - 30, 20)];
        _status.center =CGPointMake(self.imageView.center.x, self.imageView.center.y + 30);
        _status.textAlignment = NSTextAlignmentCenter;
        _status.textColor = [AppTypeTool getThemeColor];
        _status.font = [UIFont systemFontOfSize:13];
        _status.text = IMTNewCarLocalizedString(@"connecting");
    }
    return _status;
}

- (UITableView *)tableView {
    if (!_tableView) {
        double tableY = kIMTScreenHeight * 0.05 + kIMTScreenWidth * 0.7 + 20;
        double tableHeight = ScreenHeight - tableY - kIMTNavigationBarHeight - 50 - 30 - TABBAR_BEYOND_HEIGHT;
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, tableY, ScreenWidth, tableHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 10 + kIMTBottomBarOffset)];
        _tableView.separatorInset = UIEdgeInsetsZero;
        
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _tableView;
}

- (UIButton *)bottomButton {
    if (!_bottomButton) {
        _bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _bottomButton.frame = CGRectMake(kIMTScreenWidth * 0.1, kIMTScreenHeight - kIMTNavigationBarHeight - TABBAR_BEYOND_HEIGHT -  50 - 20, kIMTScreenWidth * 0.8, 50);
        [_bottomButton addTarget:self action:@selector(bottomClick) forControlEvents:UIControlEventTouchUpInside];
        _bottomButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _bottomButton.layer.masksToBounds = true;
        _bottomButton.layer.cornerRadius = 25;
        _bottomButton.layer.borderColor = kIMTDefaultLightBlack.CGColor;
        _bottomButton.layer.borderWidth = 1.0;
        [_bottomButton setTitleColor:kIMTDefaultLightBlack forState:UIControlStateNormal];
    }
    return _bottomButton;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
